package com.example.demo.test.lecture.algorithm.base;

public class Bubble {
    public static void main(String[] args) {
        int[] arraysV = {4, 1, 18, 8, 13, 7};
        int[] result = sortArray(arraysV);
        result = selectSort(arraysV);
        for (int i = 0; i < result.length; i++) {
            System.out.println("arr[" + i + "]: " + result[i]);
        }

        char[] arr = { 'a', 'b', 'c', 'd'};
        fullSort(arr, 0, arr.length - 1);
    }

    /**
     * Bubble Sort
     *
     * @param args
     * @return
     */
    public static int[] sortArray(int[] args) {
        if (args == null || args.length == 0) {
            return args;
        }
        int length = args.length;
        for (int i = 0; i < length - 1; i++) {
            for (int j = 0; j < length - 1 - i; j++) {
                if (args[j + 1] > args[j]) {
                    int tmp = args[j + 1];
                    args[j + 1] = args[j];
                    args[j] = tmp;
                }
            }
        }
        return args;
    }

    public static int[] selectSort(int[] args) {
        if (args == null || args.length == 0) {
            return args;
        }
        int length = args.length;
        for (int i = 0; i < length; i++) {
            int minIndex = i;
            for (int j = i; j < length; j++) {
                if (args[j] < args[minIndex]) {
                    minIndex = j;
                }
            }
            int tmp = args[i];
            args[i] = args[minIndex];
            args[minIndex] = tmp;
        }
        return args;
    }

    public static void fullSort(char[] arr, int start, int end) {
        // 递归终止条件
        if (start == end) {
            for (char i : arr) {
                System.out.print(i);
            }
            System.out.println();
            return;
        }
        for (int i = start; i <= end; i++) {
            System.out.println("i: " + i + ", start: " + start);
            swap(arr, i, start);
            fullSort(arr, start + 1, end);
            swap(arr, i, start);
        }
    }

    private static void swap(char[] arr, int i, int j) {
        char tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
}
